import isFunction from './isFunction'
import isFunctionComponent from './isFunctionComponent'
import mountNativeElement from './mountNativeElement'
export default function mountComponent(virtualDOM, container, oldDOM) {
    let nextVirtualDOM = null
    let component = null
    // 判断是函数组件还是类组件
    if (isFunctionComponent(virtualDOM)) {
        console.log("函数组件")
        nextVirtualDOM = buildFunctionComponent(virtualDOM)

    } else {
        console.log("类组件")
        nextVirtualDOM = builClassComponent(virtualDOM)
        component = nextVirtualDOM.component
    }
    if (isFunction(nextVirtualDOM)) {
        mountComponent(nextVirtualDOM, container, oldDOM)
    } else {
        mountNativeElement(nextVirtualDOM, container, oldDOM)
    }
    if(component){
        component.componentDidMount()
    }
    if(component?.props?.ref){
        component.props.ref(component)
    }
}

function buildFunctionComponent(virtualDOM) {
    return virtualDOM.type(virtualDOM.props || {})
}
function builClassComponent(virtualDOM) {
    const component = new virtualDOM.type(virtualDOM.props || {})
    const nextVirtualDOM = component.render()
    nextVirtualDOM.component = component
    return nextVirtualDOM
}